'use client'
import "./index.css"
import React, { useEffect, useState } from 'react';
import type {FC} from 'react'
import type { TableProps } from 'antd';
import {Button, Space, Table,Input,Popover,Modal } from 'antd'
import UploadFile from '@/app/components/upload-file';
import ServiceClient from '@/app/api/utils/serviceClient'
import TwoDifyClient from '@/app/api/utils/twoDifyClient'
import {SERVICE_URL} from '@/config' 
import { SearchOutlined,LeftCircleOutlined,PlusCircleOutlined  } from "@ant-design/icons";
import type { GetProps } from 'antd';
import { useRouter } from 'next/navigation';
import {API_URL} from '@/config'
import Link from 'next/link'
import AddKnowLedge from '@/app/components/knowledge'
const { Search } = Input;
type SearchProps = GetProps<typeof Input.Search>;
interface DataType {
  id: string;
  created_at : string;
  name: string;
  indexing_status:string //"completed"
}
type IParam ={
  keyword:string
  page:number
  limit:number
  dataset_id:string
}

const columns: TableProps<DataType>['columns'] = [
  {
    title: '文件名',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '文件字数',
    dataIndex: 'word_count',
    key: 'word_count',
  },{
    title: '状态',
    dataIndex: 'indexing_status',
    key: 'indexing_status',
    render: (indexing_status) => <>{indexing_status==='completed'?<div className="text-lime-400">正常解析</div>:<div className="text-red-800">有误</div>}</>,
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    render: (created_at) => <>{timestampToString(created_at)}</>,
  },
  {
    title: '操作',
    key: 'action',
    render: (_, record) => (
      <Space size="middle">
        <a onClick={()=>{downloadDocMethod(record)}}>下载</a>
         <a className=" text-gray-600">|</a>
        <a>删除</a>
      </Space>
    ),
  },
];


let docData: DataType[] = [];
let knowledgeData:any =[]


function timestampToString(timestamp:any) {
  const date = new Date(timestamp);
  return date.toLocaleString(); // 返回本地时间字符串
}
const menStyle={
  border:'2px solid #1677ff67',
  borderRadius:'10px'
}
const param:IParam={keyword:"",page:1,limit:10,dataset_id:""}


const sApi =new ServiceClient()
const tApi =new TwoDifyClient()
//下载文件
const downloadDocMethod =(row:any)=>{
  tApi.downloadDocument({dataset_id:param.dataset_id,document_id:row.id}).then(res=>{   
    window.location.href=API_URL.split('/v1')[0]+res.data.download_url
  })
}
//创建知识库数据集接口
type ICreateKdData={
  name:string,
  description:string,
  indexing_technique :string,        //模式 high_quality 高质量  or economy 经济
  permission: string               //仅自己 only_me or all_team_members 所有团队成员 or partial_members 部分团队成员
  Provider:string               //vendor 上传文件
}

//函数入口
const Knowledge:FC =()=>{

  const router = useRouter()
  const [menuVal,setMenuVal] = useState("")

  useEffect(()=>{

    //获取知识库列表
    tApi.datasets().then(res=>{
        knowledgeData=[]
        res.data.data.forEach(e => {
          knowledgeData.push(e)
        });
        //根据所选择的知识库获取里面文件列表
        getDataList(knowledgeData[0].id)
        
    })

  },[]) 

  const getDataList=(id:string)=>{
    
    param.dataset_id=id
    tApi.documents(param).then(res=>{
      docData=[]
      res.data.data.forEach(e => {
        docData.push(e)
      });
      setMenuVal(id)
     
    })
  }

  const [pageSize, setPageSize] = useState(5); // 默认每页5行
 
  const handlePageSizeChange = value => {
    setPageSize(Number(value)); // 更新每页行数
  };
  const onSearch: SearchProps['onSearch'] = (value, _e, info) =>{
    console.log(info?.source, value)
    
  };
  const reMainMethod =()=>{
    //返回主页
    router.back()
  }
  return(
    <div className='flex'>

      <div className='w-2/6 h-screen bg-slate-100 flex flex-col items-center'>
          <div className=" m-3 p-4  w-5/6 bg-blue-400 text-white flex justify-center items-center rounded-xl">
            <div>智能体分类</div>
          </div>
         { 
            knowledgeData.map(e=>{
              //return <Button style={butonStyle} type="dashed">{e.title}</Button>
              return <div onClick={()=>getDataList(e.id)} className='rounded-xl know-container flex justify-start items-center w-5/6 bg-white p-2 m-2 text-center text-gray-700' style={menuVal===e.id?menStyle:{}}>
                <div className="bao-icon pdf-icon w-20"><img src={SERVICE_URL+e.image_url} alt="" className="w-20"/></div>
                <div className='flex flex-col items-start'>
                  <div style={{fontWeight:"600",fontSize:".8rem"}}>{e.name}</div>
                  <div className='text-xs text-gray-400 text-left' style={{fontWeight:"300",fontSize:"0.7rem"}}>{e.description}</div>
                </div>
                
              </div>
            })
         }
      </div>
      <div className='flex flex-col w-4/6'>
          <div className=' w-full h-20 flex items-center justify-between pr-5' style={{lineHeight:"5rem"}}>
              <div className="flex ml-5">
                <Button type="link" shape="circle" icon={<LeftCircleOutlined />} className="mr-10" onClick={reMainMethod}>返回主页</Button>
                <div>

                </div>
                { false && <Search placeholder="按文件名模糊查询" onSearch={onSearch} enterButton />}
              </div>
                 <UploadFile knowledgeId={menuVal} title="点击上传" extIntro="可以上传知识库(docx、xlsx、pdf、png 、jpg、txt类型的文件)"/> 
          </div>
          <div>
            <Table<DataType> className=' bg-slate-50 h-80 w-full' columns={columns} dataSource={docData} pagination={{ pageSize: 5 }}/>
          </div>
        </div>
    </div>
  )

}
export default Knowledge